package com.echo.neocommunity.config;

import com.echo.neocommunity.pojo.LoginTicket;
import com.echo.neocommunity.pojo.User;
import com.echo.neocommunity.service.impl.UserServiceImpl;
import com.echo.neocommunity.utils.CookieUtils;
import com.echo.neocommunity.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ticket = CookieUtils.getValue(request, "ticket");
        if(ticket!=null){
            LoginTicket loginTicketByTicket = userService.getLoginTicketByTicket(ticket);
           if(loginTicketByTicket!=null && loginTicketByTicket.getStatus()!=1 && loginTicketByTicket.getExpired().after(new Date())){
               User userById = userService.getUserById(loginTicketByTicket.getUserId());
               if(userById!=null){
                   hostHolder.setUser(userById);
               }
           }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(hostHolder.getUser()!=null && modelAndView!=null){
            modelAndView.addObject("loginUser",hostHolder.getUser());
        }


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();
    }
}
